package com.test.mooan.labama.dialog_boom;

import static com.test.mooan.labama.utils_boom.Permissionutil_boom.Permission_Code_Sms;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;

import com.test.mooan.labama.R;
import com.test.mooan.labama.adapter_boom.PermissionViewAdapter_boom;
import com.test.mooan.labama.bean_boom.PermissionInfo_boom;
import com.test.mooan.labama.constants_boom.Constant_boom;
import com.test.mooan.labama.listener_boom.PermissionListener_boom;
import com.test.mooan.labama.utils_boom.helper_boom.UserInfoHelper_boom;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class AllPermissionDialog_boom extends Dialog {

    private static boolean isShow = false;

    private ViewPager2 viewPager2;
    private PermissionViewAdapter_boom permissionViewAdapter;
    private final ArrayList<PermissionInfo_boom> infos = new ArrayList<>();

    private final ArrayList<View> pointViews = new ArrayList<>();

    private final Context context;

    private final Runnable processRunnable;

    private final String pageTag = "DIALOG_PERMISSION";

    public AllPermissionDialog_boom(@NonNull Context context, @NonNull Runnable processRunnable) {
        super(context);
        this.context = context;
        this.processRunnable = processRunnable;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_all_permission_boom);

        setCancelable(false);
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCanceledOnTouchOutside(false);
        getWindow().setBackgroundDrawableResource(R.color.trans);

        viewPager2 = findViewById(R.id.dialog_permission_vp_page);
        LinearLayout pointLayout = findViewById(R.id.dialog_permission_layout_diangroup);

        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, Manifest.permission.READ_SMS)){
            infos.add(new PermissionInfo_boom(
                    R.drawable.icon_permission_sms,
                    getContext().getString(R.string.permission_sms_title),
                    getContext().getString(R.string.permission_sms_text),
                    smsPermissionListneer)
            );

            View pv = View.inflate(context,R.layout.view_point_boom,null);
            pv.setBackgroundResource(R.drawable.bg_point_true);
            pointViews.add(pv);
            pointLayout.addView(pv);

            infos.add(new PermissionInfo_boom(
                    R.drawable.icon_permission_applist,
                    getContext().getString(R.string.permission_applist_title),
                    getContext().getString(R.string.permission_applist_text),
                    applistPermissionListneer)
            );

            View pv1 = View.inflate(context,R.layout.view_point_boom,null);
            pv1.setBackgroundResource(R.drawable.bg_point_true);
            pointViews.add(pv1);
            pointLayout.addView(pv1);

        }


        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE)){
            infos.add(new PermissionInfo_boom(
                    R.drawable.icon_permission_phone,
                    getContext().getString(R.string.permission_phonestate_title),
                    getContext().getString(R.string.permission_phonestate_text),
                    phonestatePermissionListneer)
            );

            View pv = View.inflate(context,R.layout.view_point_boom,null);
            pv.setBackgroundResource(R.drawable.bg_point_true);
            pointViews.add(pv);
            pointLayout.addView(pv);
        }

        permissionViewAdapter = new PermissionViewAdapter_boom(getContext(),infos);
        viewPager2.setAdapter(permissionViewAdapter);

        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                for (int i = 0 ; i<pointViews.size(); i++){
                    View v = pointViews.get(i);
                    if (i==position) v.setBackgroundResource(R.drawable.bg_point_true);
                    else v.setBackgroundResource(R.drawable.bg_point_false);
                }
            }
        });

    }

    private final PermissionListener_boom smsPermissionListneer = new PermissionListener_boom() {
        @Override
        public void onPermissionAgree() {

           try {
               UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_SMS_AGREE_CLICK").toUpperCase());

               Runnable agreeRunnable = () -> {
                   if (context instanceof Activity)
                       EasyPermissions.requestPermissions((Activity) context, context.getString(R.string.launch_permissions_sms), Permission_Code_Sms, Manifest.permission.READ_SMS);
               };

               PermissionViewAdapter_boom.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).gHolder();

               if (holder.getCheck()) agreeRunnable.run();
               else {
                   new PermissionAgreeDialog_boom(context,null,() -> {
                       holder.setCheck(true);
                       agreeRunnable.run();
                   }).show();
               }
           }catch (Exception e){
               if (Constant_boom.Debug) e.printStackTrace();
           }

        }

        @Override
        public void onPermissionDeny() {
            UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_SMS_DENY_CLICK").toUpperCase());
            nextPage();
        }
    };

    private final PermissionListener_boom applistPermissionListneer = new PermissionListener_boom() {
        @Override
        public void onPermissionAgree() {

            try {
                UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_APPS_AGREE_CLICK").toUpperCase());

                Runnable agreeRunnable = () -> {
                    permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).sViewAgree();
                    nextPage();
                };

                PermissionViewAdapter_boom.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).gHolder();

                if (holder.getCheck()) agreeRunnable.run();
                else {
                    new PermissionAgreeDialog_boom(context,null,() -> {
                        holder.setCheck(true);
                        agreeRunnable.run();
                    }).show();
                }
            }catch (Exception e){
                if (Constant_boom.Debug) e.printStackTrace();
            }
        }

        @Override
        public void onPermissionDeny() {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_APPS_DENY_CLICK").toUpperCase());

            nextPage();

        }
    };


    private final PermissionListener_boom phonestatePermissionListneer = new PermissionListener_boom() {
        @Override
        public void onPermissionAgree() {

            try {
                UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_PHONE_STATE_AGREE_CLICK").toUpperCase());

                Runnable agreeRunnable = () -> {
                    if (viewPager2 != null) {
                        permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).sViewAgree();
                        nextPage();
                    }
                };

                PermissionViewAdapter_boom.PermissionDialogHolder holder = permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).gHolder();

                if (holder.getCheck()) agreeRunnable.run();
                else {
                    new PermissionAgreeDialog_boom(context,null,() -> {
                        holder.setCheck(true);
                        agreeRunnable.run();
                    }).show();
                }
            }catch (Exception e){
                if (Constant_boom.Debug) e.printStackTrace();
            }
        }

        @Override
        public void onPermissionDeny() {

            UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_PHONE_STATE_DENY_CLICK").toUpperCase());

            if (context!=null && context instanceof Activity && viewPager2 != null) {
                permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).sViewAgree();
                nextPage();
            }
        }
    };


    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (requestCode == Permission_Code_Sms) {
            if (EasyPermissions.somePermissionPermanentlyDenied((Activity) context, perms)) {
                new AppSettingsDialog.Builder((Activity) context).build().show();
            } else {
                UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SMS_REQUEST_DENY_CLICK").toUpperCase());
                nextPage();
            }
        }
    }

    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (requestCode == Permission_Code_Sms) {
            UserInfoHelper_boom.gInstance().addEventPoint((pageTag + "_SMS_GRANTED_CLICK").toUpperCase());

            if (viewPager2 != null) {
                permissionViewAdapter.getInfo(viewPager2.getCurrentItem()).sViewAgree();
                if (infos.get(0).gHolder() != null) nextPage();
            }
        }
    }


    public void nextPage(){
        if (viewPager2==null){
            if (processRunnable!=null) processRunnable.run();
            return;
        }
        int nextPageIndex = viewPager2.getCurrentItem()+1;
        if (nextPageIndex>=0&&permissionViewAdapter.getItemCount()>nextPageIndex) viewPager2.setCurrentItem(nextPageIndex);
        else if (processRunnable!=null) processRunnable.run();
    }

    @Override
    public void show() {
        if (isShow) return;
        isShow = true;
        UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_START").toUpperCase());
        super.show();
    }

    @Override
    public void dismiss() {
        isShow = false;
        UserInfoHelper_boom.gInstance().addEventPoint((pageTag+"_END").toUpperCase());
        super.dismiss();
    }

}
